package com.baidu.fsg.uid.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Data
@Configuration
@ConfigurationProperties("idmapping")
public class IdMappingDisableConfiguration implements WebMvcConfigurer, Filter {

    List<String> disable;
    public static ThreadLocal<Boolean> isDisable = new ThreadLocal<Boolean>();

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Bean
    public FilterRegistrationBean idMappingDisableFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setOrder(0);
        filterRegistrationBean.setFilter(this);
        filterRegistrationBean.setName("IdMappingDisable");
        filterRegistrationBean.addUrlPatterns("*.do","*.api","*.notify");
        return filterRegistrationBean;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        try{
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String req = request.getServletPath();
            if(disable != null && disable.stream().filter(u -> antPathMatcher.match(u,req)).count() >= 1 ){
                isDisable.set(true);
            }else{
                isDisable.set(false);
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }finally {
            isDisable.remove();
        }

    }
}
